import Config from "./config";
import axios from 'axios';
import API from "@/api";
import { goRouter } from "./../index"

const errorFunction = function(response, tipConfig) {
    Config.tipShow(response, tipConfig, 'error');
    if(response.code == '406') {
        // 判断登录是否过期，跳转登录页
        goRouter('/login');
    };
    return response.data;
}

const successFunction = function(res, tipConfig) {
    // console.log(res, tipConfig,'success成功请求');
    Config.tipShow(res.data, tipConfig, 'success');
    return res.data
}

let promises = [] 


const posUrl =  function(url) { /* 判断url是否为绝对路径 */
    return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
}
const setConfigAxios = function(options = {}) {
    options.baseURL = Config.options.baseURL;
    options.responseType = options.responseType || Config.options.responseType
    options.timeout = options.timeout || Config.options.timeout
    options.headers = { ...Config.options.headers, ...options.headers }
	return axios.create(Config.options);
}
const instance = setConfigAxios({});

instance.interceptors.request.use( 
    config => {
    // 在发送请求之前做些什么    1. 判断url是否为绝对路径，
    if (!posUrl(config.url)) {
        const reqURL = config.url.split('.');
        if( reqURL.length == 2 ){
            config.url = API[reqURL[0]][reqURL[1]]
        }else if( reqURL.length == 3 ){
            config.url = API[reqURL[0]+'/'+reqURL[1]][reqURL[2]]
        }
    }
    const connectId = Symbol(config.url);
    let tipConfig = {};
    promises.push(connectId)
    config.connectId = connectId;

    if(!!config.data && config.data.toString().indexOf('tipConfig')){
        // console.log(config,"????")
        let param = config.data
        tipConfig = param.tipConfig;
        delete param.tipConfig;
        config.data = param;
    }
    if(!!config.tipConfig){
        tipConfig = config.tipConfig
    }

    config.tipConfig = tipConfig;

    if (!!config.tipConfig?.upLoadForm) {
        config.data = config.data.form
    }

    const token = localStorage.getItem('token') || '';
    config.headers.token = token
    return config;
}, error => {
    return Promise.reject(error);
});

instance.interceptors.response.use(function (response) {
    let tipConfig = {...Config.tipConfig, ...response.config.tipConfig};
    if(tipConfig.codeFile){
        return successFunction(response,tipConfig)
    }
    if(response.data.success){
        return successFunction(response,tipConfig)
    }else{
        response['code'] = response.data.code;
        return errorFunction(response, tipConfig)
    }
}, function (error) {
    error.response['code'] = error.response.status;
    errorFunction(error.response, error.response.config.tipConfig)
    return Promise.reject(error);
});

export default instance;
